package controllers
{
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.CursorManager;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.swizframework.controller.AbstractController;

	public class MidiaController extends AbstractController implements IMidiaController
	{
        [Autowire(bean="midiaService")]
        public var midiaService : RemoteObject;
        		
		// A coleção de mídias da appModel será injeta nesta variável local.
		[Autowire( bean="appModel", property="midias" )]
		public var midias:ArrayCollection;
        		
		public function MidiaController()
		{
			super();
		}
		
		[Mediate( event="MidiaEvent.SALVAR_MIDIA", properties="midia" )]
		public function salvarMidia(midia:Object):void
		{
			//executeServiceCall(midiaService.save(midia), saveMidia_results);
			midiaService.addEventListener(ResultEvent.RESULT, updateResultHandler);
			midiaService.addEventListener(FaultEvent.FAULT, faultHandler);
			var call:AsyncToken = midiaService.update({id:midia.id, midia:midia});
		}
		
		[Mediate( event="MidiaEvent.LISTAR_MIDIAS" )]
		public function findAll():void
		{
			//Serviço AMF para buscar midias
			midiaService.addEventListener(ResultEvent.RESULT, findAllResultHandler);
			midiaService.addEventListener(FaultEvent.FAULT, faultHandler);
			var call:AsyncToken = midiaService.index();			
		}
		
		private function findAllResultHandler(event : ResultEvent):void
		{
			//midias = new ArrayCollection(event.result as Array);
			//var arrayMidias = event.result as Array;
			midias.removeAll();
			
			for each( var _midia:Object in (event.result as Array) )
			{
				midias.addItem(_midia);	
			}
			midiaService.removeEventListener(ResultEvent.RESULT, findAll);
			CursorManager.removeBusyCursor();
		}
		
		private function updateResultHandler(event : ResultEvent):void
		{
			//Alert.show("Ok!", "updateResultHandler");
			midiaService.removeEventListener(ResultEvent.RESULT, updateResultHandler);
			
		}
		
		private function atualizaListaMidiasMidias(midia:Object)
		{
			for each( var _midia:Object in midias )
			{
				if( _midia.id == midia.id )
				{
					_midia.id = midia.id;
					_midia.nome = midia.nome;
					_midia.anoLancamento = midia.anoLancamento;
					break;
				}
			}					
		}
		
		private function faultHandler(event : FaultEvent):void{
			Alert.show(event.fault.message, 'HTTP Service Error');
			midiaService.removeEventListener(FaultEvent.FAULT, faultHandler);
			CursorManager.removeBusyCursor();
		}
		
	}
}